<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <h1 id="myh1"></h1>

  <script>
    // 待处理的字符串
    // const str = 'JS ArrayBuffer about js'

    // 需求：把 js 替换为 javascript
    // const result = str.replace('js', 'javascript')
    // console.log(result)

    // const result = str.replace(/js/gi, 'javascript')
    // console.log(result)

    // -------------------------

    // const kw = 'js'
    // const str = 'JS ArrayBuffer Js about js'

    // //      /js/ig
    // const reg = new RegExp(kw, 'ig')
    // const result = str.replace(reg, '<span style="color: red;">js</span>')
    // console.log(result)
    // document.querySelector('#myh1').innerHTML = result


    // -----------------------------

    const kw = 'js'
    const str = 'JS ArrayBuffer Js about js'

    //      /js/ig
    const reg = new RegExp(kw, 'ig')
    // 形参中的 val 就是每次匹配到的值
    const result = str.replace(reg, function (val) {
      return `<span style="color: red;">${val}</span>`
    })

    // 第一次替换的结果：
    // <span>JS</span> ArrayBuffer Js about js
    // 第二次替换的结果：
    // <span>JS</span> ArrayBuffer <span>Js</span> about js
    // 第三次替换的结果：
    // <span>JS</span> ArrayBuffer <span>Js</span> about <span>js</span>

    document.querySelector('#myh1').innerHTML = result


    // const result = str.replace(reg, '<span style="color: red;">js</span>')

  </script>
</body>

</html>